'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');
const utils = require('../utils/utils');
class UserController extends Controller {
  // 验证码
  async messageCode() {
    const { ctx } = this;
    // 获取前端的
    const { phone } = ctx.query;
    const msgCode = utils.getLengthRandom(6);
    ctx.session.msgCode = msgCode;
    console.log(phone);
    ctx.body = {
      code: 1,
      message: `验证码[${msgCode}]已发送手机[${phone}]`,
    };
  }

  async info() {
    const { ctx } = this;
    ctx.body = {
      code: 1,
      data: ctx.userInfo,
    };
  }
  // 登陆
  async login() {
    const { ctx } = this;
    const { code, phone } = ctx.request.body;
    if (code === ctx.session.code) {
      const user = await ctx.service.user.find(phone);
      if (user.length > 0) {
        const token = jwt.sign({ ...user }, 'chb');
        ctx.cookies.set('token', token, {
          maxAge: 1000 * 60 * 60 * 24 * 30,
          httpOnly: false,
        });
        ctx.body = {
          code: 0,
          msg: '登陆成功',
        };
      } else {
        ctx.throw(422, '用户不存在');
      }
    }
  }
}

module.exports = UserController;
